/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-01-04
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-02-08
 * @Description: 布局容器
 */
import 'package:flutter/material.dart';
import 'package:chat_client/screens/chat/chat_list_screen.dart';
import 'package:chat_client/screens/contacts/contacts_screen.dart';
import 'package:chat_client/screens/discover/discover_screen.dart';
import 'package:chat_client/screens/profile/profile_screen.dart';
import 'package:chat_client/screens/functions/add_friend.dart';
import 'package:chat_client/widgets/c_popup_menu.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<StatefulWidget> createState() {
    return _HomeScreenState();
  }
}

// 私有
class _HomeScreenState extends State<HomeScreen> {
  // 底部导航栏页面列表
  final List<Widget> _pages = [
    const ChatListScreen(), // 聊天列表页面
    const ContactsScreen(), // 通讯录页面
    const DiscoverScreen(), // 发现页面
    const ProfileScreen(), // 个人资料页面
  ];

  // 底部导航栏索引
  int _currentIndex = 0;

  // 控制页面切换的PageController
  final PageController _pageController = PageController();

  // 底部导航栏点击事件
  void _onTap(int index) {
    setState(() {
      _currentIndex = index;
    });
    _pageController.animateToPage(index,
        duration: const Duration(milliseconds: 300), curve: Curves.ease);
  }

  // 构建底部导航栏项
  BottomNavigationBarItem _buildBottomNavItem(IconData icon, String label) {
    return BottomNavigationBarItem(
      icon: Icon(icon),
      label: label,
    );
  }

  // 动态获取 AppBar 的标题
  String _getAppBarTitle() {
    switch (_currentIndex) {
      case 0:
        return '聊天';
      case 1:
        return '通讯录';
      case 2:
        return '发现';
      default:
        return '';
    }
  }

  final LayerLink _layerLink = LayerLink();
  OverlayEntry? _overlayEntry;

  // 显示菜单弹窗
  void _showPopup(BuildContext context) {
    final renderBox = context.findRenderObject() as RenderBox;
    final offset = renderBox.localToGlobal(Offset.zero); // 获取按钮的绝对位置

    _overlayEntry = OverlayEntry(
        builder: (context) => PopupMenu(
              onClose: () => _closePopup(),
              offset: offset,
              layerLink: _layerLink,
              menuItems: [
                MenuItem(
                  icon: Icons.person_add,
                  text: '添加好友',
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => const AddFriendScreen()),
                    );
                  },
                ),
                MenuItem(
                  icon: Icons.group_add,
                  text: '发起群聊',
                  onTap: () {
                    print('发起群聊');
                  },
                ),
                MenuItem(
                  icon: Icons.qr_code_scanner,
                  text: '扫二维码',
                  onTap: () {
                    print('扫一扫');
                  },
                ),
              ],
            ));

    Overlay.of(context).insert(_overlayEntry!);
  }

  // 关闭弹窗
  void _closePopup() {
    _overlayEntry?.remove();
    _overlayEntry = null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _currentIndex == 3
          ? AppBar(
              backgroundColor: Colors.transparent) // 隐藏 AppBar，当 index 为 3 时
          : AppBar(
              title: Text(_getAppBarTitle()), // 动态设置标题
              centerTitle: true, // 设置标题居中
              actions: [
                IconButton(icon: const Icon(Icons.search), onPressed: () {}),
                CompositedTransformTarget(
                  link: _layerLink,
                  child: IconButton(
                    icon: const Icon(Icons.add_circle_outline),
                    onPressed: () => _showPopup(context),
                  ),
                ),
              ],
            ),
      body: PageView(
        controller: _pageController,
        onPageChanged: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
        children: _pages,
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: _onTap,
        items: [
          _buildBottomNavItem(Icons.chat, '消息'),
          _buildBottomNavItem(Icons.contacts, '通讯录'),
          _buildBottomNavItem(Icons.explore, '发现'),
          _buildBottomNavItem(Icons.manage_accounts, '我'),
        ],
      ),
    );
  }
}
